<template>
    <div>
        <div class="m-alert">
            <span class="el-icon-info"></span>
            <div>
                <div>这是一个增删改查的模板<el-button type="text" style="padding: 0;height: 0;" @click="$message({message:'😀'})">😀</el-button></div>
            </div>
        </div>

        <div class="interspaceH"></div>

        <!--查询面板-->
        <el-card class="box-card">
            <el-input v-model="queryData.name" placeholder="名称" size="small"></el-input>
            <el-select v-model="queryData.sex" placeholder="性别" size="small">
                <el-option v-for="item in dictionary.sex" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
            </el-select>
            <el-date-picker
                    size="small"
                    v-model="queryData.createTime"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>

            <el-button type="primary" size="small" @click="queryDataHandle">查询</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button plain size="small" @click="resetQuery">重置</el-button>
        </el-card>

        <div class="interspaceH"></div>

        <!--列表面板-->
        <el-card class="box-card">
            <el-button type="primary" size="small" @click="formHandle('add')">+ 添加</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button plain type="primary" size="small" @click="deleteHandle()">批量删除</el-button>
            <div class="interspaceH"></div>
            <el-table @selection-change="tableRowChange" :data="pageDataSource"
                      :header-cell-style="{background:'#F3F4F7',color:'#555'}" style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="name" label="名称"></el-table-column>
                <el-table-column prop="sex" label="性别" :formatter="formatter"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" :formatter="formatter"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button @click="detailHandle(scope.row)" type="text" size="small">详情</el-button>
                        <el-divider direction="vertical"></el-divider>
                        <el-button @click="formHandle('edit', scope.row)" type="text" size="small">修改</el-button>
                        <el-divider direction="vertical"></el-divider>
                        <el-button @click="deleteHandle(scope.row)" type="text" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="interspaceH"></div>

            <el-pagination @size-change="queryDataHandle(pagePagination.currentPage,$event)"
                           @current-change="queryDataHandle($event,pagePagination.pageSize)"
                           :current-page="pagePagination.currentPage"
                           :page-sizes="pagePagination.pageSizes" :page-size="pagePagination.pageSize"
                           layout="total, sizes, prev, pager, next"
                           :total="dataSource.length">
            </el-pagination>
        </el-card>
        <!--详情面板-->
        <el-dialog title="详情" :visible.sync="detailVisible" width="30%" :close-on-click-modal="false">
            <el-form ref="form" :model="detailForm" label-position="left" label-width="80px">
                <el-form-item label="名称">
                    <el-input v-model="detailForm.name" disabled size="small"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-input v-model="detailForm.sex" disabled size="small"></el-input>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-input v-model="detailForm.createTime" disabled size="small"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailVisible = false" size="small">返回</el-button>
            </span>
        </el-dialog>
        <!--添加/修改面板-->
        <el-dialog :title="formTitle" :visible.sync="formVisible" width="30%" :close-on-click-modal="false">
            <el-form ref="formPanel" :model="formData" label-position="left" label-width="80px">
                <el-form-item label="名称" prop="name" :rules="{ required: true, message: '请输入名称', trigger: 'blur' }">
                    <el-input v-model="formData.name" size="small"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="formData.sex" placeholder="性别" size="small">
                        <el-option v-for="item in dictionary.sex" :key="item.value" :label="item.label"
                                   :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="submitData()" type="primary" size="small">确定</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button @click="formVisible = false" size="small">取消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
//查询表单
const initQueryData = {
    name: '',//名称
    sex: '',//性别
    createTime: ''//创建时间
}
//添加/修改表单
const initFormData = {
    id: '',
    name: '',//名称
    sex: '0',//性别
}
//下拉列表开始
const sex = [
    {
        value: '1',
        label: '男'
    },
    {
        value: '0',
        label: '女'
    }
]
//下拉列表结束

export default {
    data() {
        return {
            //列表选中的下标
            multipleSelection: [],
            //添加/修改
            formTitle: '',
            //添加/修改是否显示
            formVisible: false,
            //详情是否显示
            detailVisible: false,
            //下拉列表种类
            dictionary: {
                sex: sex
            },
            //字段转换
            fieldType: {
                sex: "array",
                createTime: "datetime"
            },
            //查询表单
            queryData: {...initQueryData},
            //添加/修改表单
            formData: {...initFormData},
            //详情表单
            detailForm: {
                name: '',
                sex: '',
                createTime: ''
            },
            //列表数据
            dataSource: [],
            //分页后列表数据
            pageDataSource: [],
            pagePagination: {
                currentPage: 1,
                pageSizes: [10, 15, 20, 25],
                pageSize: 10,
                total: 0
            },
        }
    },
    mounted() {
        let that = this
        for (let i = 0; i < 36; i++) {
            that.dataSource.push(
                {
                    id: i,
                    name: '名称' + (i + 1),
                    sex: Math.round(Math.random()).toString(),
                    createTime: new Date()
                }
            )
        }
        //初始化执行查询方法
        this.queryDataHandle(1, 10)
    },
    methods: {
        queryDataHandle(page, rows) {
            let that = this
            let data = [...that.dataSource]
            that.pagePagination['currentPage'] = page
            that.pagePagination['pageSize'] = rows
            let length = that.dataSource.length
            that.pageDataSource = data.splice((page - 1) * rows, page * rows > length ? length - (page - 1) * rows : rows)
        },
        //重置方法
        resetQuery() {
            this.queryData = {...initQueryData}
            this.$message({
                message: '重置成功',
                type: 'success'
            });
        },
        //转换方法
        formatter(row, column) {
            let field = column.property;
            let value = row[field];
            return this.$utils.formatterForLable(field, value, this.fieldType, this['dictionary'][field]);
        },
        //列表选中方法
        tableRowChange(val) {
            this.multipleSelection = val;
        },
        //打开添加/删除弹窗方法
        formHandle(type, row) {
            if (type == 'add') {
                this.formTitle = '添加'
                this.formData = {...initFormData}
            } else if (type == 'edit') {
                this.formTitle = '修改'
                this.formData = {...row}
            }

            this.formVisible = true
        },
        //打开详情弹窗方法
        detailHandle(row) {
            this.detailForm = this.$utils.formatterForForm(row, this.fieldType, this.dictionary);
            this.detailVisible = true
        },
        //删除方法
        deleteHandle(row) {
            let that = this

            this.$confirm('是否确认删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //等于空表示批量删除
                if (row == null || row == "") {
                    that.multipleSelection.map((item) => {
                        that.dataSource.splice(item, 1)
                    })
                } else {
                    let i = 0;
                    for (i; i < that.dataSource.length; i++) {
                        if (that.dataSource[i]['id'] == row.id) {
                            break
                        }
                    }
                    that.dataSource.splice(i, 1)
                }
                that.queryDataHandle(that.pagePagination['currentPage'], that.pagePagination['pageSize'])
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //提交/修改方法
        submitData() {
            let that = this
            let dataSource = that.dataSource
            that.$refs['formPanel'].validate((valid) => {
                if (valid) {
                    if (that.formData['id'] != null && that.formData['id'] != "") {
                        for (let i = 0; i < dataSource.length; i++) {
                            if (dataSource[i].id == that.formData['id']) {
                                dataSource[i] = that.formData
                            }
                        }
                        that.dataSource = [...dataSource]
                        that.$message({
                            message: '修改成功',
                            type: 'success'
                        });
                    } else {
                        that.formData['id'] = that.$moment(new Date()).valueOf();
                        that.formData['createTime'] = new Date()
                        that.dataSource.push(that.formData)
                        that.$message({
                            message: '添加成功',
                            type: 'success'
                        });
                    }
                    that.queryDataHandle(that.pagePagination['currentPage'], that.pagePagination['pageSize'])

                    this.formVisible = false
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }
}
</script>

<style scoped>
.box-card .el-input {
    width: 200px;
}

.el-card__body .el-select {
    width: 200px;
}

.el-form-item .el-select {
    width: 100%;
}

.el-icon-info {
    color: #35abff;
    margin-right: 10px;
}
</style>



